
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.vmware.vim25.*;
import com.vmware.vim25.mo.*;
import com.vmware.vim25.mo.util.*;

/**
 * This sample shows how to get hold of the first VirtualMachine in an inventory and retrieve its properties.
 * @author sjin
 */

public class HelloVM 
{
	 static PerfCounterInfo[] pcis =null;
	public static void main(String[] args) throws Exception
	{
		
		test();
		
//		String[] temp = new String[]{"https://10.16.2.59/sdk","root","vmware"};
//
//		ServiceInstance si = new ServiceInstance(new URL(temp[0]), temp[1], temp[2], true);
//		
//		Folder rootFolder = si.getRootFolder();
//		
//		PerformanceManager perfMgr = si.getPerformanceManager();
//		
//		printInfoMaps(perfMgr);
//		
//		printInfoMap(perfMgr);
	}
	//datacenter-7
	public static void test() throws Exception{
		
		String[] temp = new String[]{"https://10.16.2.58/sdk","administrator","Xxzx@xxkjb"};

		ServiceInstance si = new ServiceInstance(new URL(temp[0]), temp[1], temp[2], true);
		
		Datacenter dcObj = (Datacenter) new InventoryNavigator(si.getRootFolder()).searchManagedEntity("Datacenter","HPDATACenter");
		
		
		//查询所有数据中心
//		ManagedEntity []dcObjs =  new InventoryNavigator(si.getRootFolder()).searchManagedEntities("Datacenter");
//		
//		for(ManagedEntity v:dcObjs){
//		
//			System.out.println(v.getName());
//	}
//		si.getServerConnection().logout();
		
	}
	
	public static void test1() throws Exception{
		
		String[] temp = new String[]{"https://10.16.2.58/sdk","administrator","Xxzx@xxkjb"};
		
//	    CommandLineParser clp = new CommandLineParser(new OptionSpec[]{}, temp);
//	   	String urlStr = clp.get_option("url");
//  	    String username = clp.get_option("username");
//	    String password = clp.get_option("password");

		ServiceInstance si = new ServiceInstance(new URL(temp[0]), temp[1], temp[2], true);
		
		
		Folder rootFolder = si.getRootFolder();
		ManagedEntity[]  vms=  new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
	
		for(ManagedEntity v:vms){
			System.out.println(v.getName());
		}
		ManagedEntity[]  vm=  new InventoryNavigator(rootFolder).searchManagedEntities("HostSystem");
		
		for(ManagedEntity v:vm){
			System.out.println(v.getName());
		}
		for(ManagedEntity v:vms){
			
			
		if(v.getName().contains("172.20.41.218")){
			
		VirtualMachine machine = (VirtualMachine) v;
		
		String os = machine.getGuest().getGuestFullName();
		
		String ip = machine.getGuest().ipAddress;
		//盘符，容量，可用空间
		GuestDiskInfo[] disk = machine.getGuest().getDisk();
		
		GuestNicInfo[] nic = machine.getGuest().getNet();
		
		GuestScreenInfo screen = machine.getGuest().getScreen();
		
		Datastore[] data = machine.getDatastores();
		
		DatastoreInfo store = data[0].getInfo();
		
		VirtualMachineConfigInfo configInfo = machine.getConfig();
		
	
		
		System.out.println(configInfo);
		System.out.println("==============================");
//		VirtualMachineCapability vmc = v.getCapability();
//		
//		System.out.println("Hello " + vm.getName());
//		System.out.println("GuestOS: " + vminfo.getGuestFullName());
//		System.out.println("Multiple snapshot supported: " + vmc.isMultipleSnapshotsSupported());
		}
		}
		
		si.getServerConnection().logout();
	}
	
	public static void test3() throws Exception{
		
		String[] temp = new String[]{"https://10.16.2.58/sdk","administrator","Xxzx@xxkjb"};

		ServiceInstance si = new ServiceInstance(new URL(temp[0]), temp[1], temp[2], true);
		
		PerformanceManager perfMgr = si.getPerformanceManager();
		
		Folder rootFolder = si.getRootFolder();
		
		ManagedEntity[]  vm=  new InventoryNavigator(rootFolder).searchManagedEntities("HostSystem");
		
		PerfCounterInfo[] infos = perfMgr.queryPerfCounterByLevel(1);
		
		for(PerfCounterInfo info:infos){
			
		}
		
		for(ManagedEntity v:vm){
			System.out.println("hostsystem="+v.getName());
			
			HostSystem s = (HostSystem) v;
			
			HostHardwareInfo in = s.getHardware();
			
			HostConfigInfo info = s.getConfig();
			
			VirtualMachine[] mas = s.getVms();
			
			for(VirtualMachine v1:mas){
				
				VirtualMachineConfigInfo con = 	v1.getConfig();
				
				
				v1.getGuest().getDisk();
				
				System.out.println("virtualmachine="+v1.getName()+"--------ip="+v1.getGuest().getIpAddress());
			}
		}
	}
	
	public static void test4() throws Exception{
		
		String[] temp = new String[]{"https://10.16.2.59/sdk","root","vmware"};

		ServiceInstance si = new ServiceInstance(new URL(temp[0]), temp[1], temp[2], true);
		
		Folder rootFolder = si.getRootFolder();
		
		ManagedEntity[]  vm=  new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
		
		PerformanceManager perfMgr = si.getPerformanceManager();
	
		PerfCounterInfo[] counts = perfMgr.getPerfCounter();
		
		for(PerfCounterInfo info:counts){
			
			ElementDescription is = info.getGroupInfo();
			info.getNameInfo();
			int[] ss = info.getAssociatedCounterId();
			String s = is.getSummary();
			
			System.out.println(is);
		}
		for(ManagedEntity v:vm){
			
			PerfProviderSummary summary = perfMgr.queryPerfProviderSummary(v);
			
//			Integer t = perfMgr.queryPerfProviderSummary(v).getRefreshRate();
//			PerfMetricId[] id = perfMgr.queryAvailablePerfMetric( v, null, null,t);
//			
//			for(PerfMetricId metric:id){
//				if(metric==null){
//					break;
//				}
//				String s = metric.getInstance();
//				
//				System.out.println(s);
//			}
//			System.out.println("=====");
			
		}
		si.getServerConnection().logout();

		
	}
	
	public static void test5() throws Exception{
		String[] temp = new String[]{"https://10.16.2.59/sdk","root","vmware"};

		ServiceInstance si = new ServiceInstance(new URL(temp[0]), temp[1], temp[2], true);
		
		Folder rootFolder = si.getRootFolder();
		
		PerformanceManager perfMgr = si.getPerformanceManager();
		
	    Map colNameMap = getCounterInfoMap(perfMgr);
	    
	    PerfQuerySpec qSpec = new PerfQuerySpec();
	    
	    
	    VirtualMachine targetVm = (VirtualMachine) new InventoryNavigator(rootFolder).searchManagedEntity("VirtualMachine","ESB[172.20.41.218]");;
	    VirtualMachineConfigInfo  config = targetVm.getConfig();  
	    qSpec.setEntity(targetVm.getMOR());
		
	    Calendar curTime = si.currentTime();
	    Calendar startTime = (Calendar)curTime.clone();
	    startTime.roll(Calendar.HOUR, -1);
	    qSpec.setStartTime(startTime);
	 
	    Calendar endTime = (Calendar)curTime.clone();
	    qSpec.setEndTime(endTime);
	    PerfProviderSummary summary = perfMgr.queryPerfProviderSummary(targetVm);
	    int perfInterval = summary.getRefreshRate();
	    qSpec.setIntervalId(perfInterval);
	    PerfMetricId[] pmis = null;
        pmis =perfMgr.queryAvailablePerfMetric(
          targetVm,
          null,
          null,
          perfInterval);
        
        ArrayList<PerfMetricId> arrayList = new ArrayList<>();
        
        for(int i=0;i<pmis.length;i++){
        	
        	PerfMetricId id = pmis[i];
        	
        	int countid = id.getCounterId();
        	System.out.println();
        	if(1==countid||2==countid||3==countid||4==countid){
        		arrayList.add(id);
        	}
        }
        PerfMetricId[] newpmis = arrayList.toArray(new PerfMetricId[arrayList.size()]);
        qSpec.setMetricId(newpmis);
        qSpec.setFormat("normal");
        PerfEntityMetricBase[] pembss = perfMgr.queryPerf(new PerfQuerySpec[]{qSpec});
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        String seriesStr = "";
        //取得したデータから表示用データを標準出力する
        for (PerfEntityMetricBase pemb : pembss){  //エンティティごとの値ループ
        
        	
          PerfEntityMetric pem = (PerfEntityMetric) pemb;
   
          //サンプルの時刻情報
          PerfSampleInfo[] info = pem.getSampleInfo();
   
          //値の取得
          PerfMetricSeries[] value = pem.getValue();
          int row =0;
   
          for (PerfMetricSeries pmsValue:value){//系列毎の値ループ
            int counterId = pmsValue.getId().getCounterId();
   
            //カウンタID:2 = CPU利用率 、カウンタID:24 = メモリ使用量 || counterId == 24
            if (counterId == 2||counterId==24){
   
              //系列ごとの値を取得する
              PerfMetricIntSeries pmiss = (PerfMetricIntSeries)pmsValue;
             
              long[] longs = pmiss.getValue();
              
              System.out.print("[");
   
              for (int i = 0 ; i < longs.length ; i++){
                System.out.print("[\""+sdf.format(info[i].getTimestamp().getTime())+"\","+longs[i]+"]");
                if (i < longs.length -1) {
                  System.out.print(",");
                }
              }
              System.out.println("],");
   
              //系列の情報を出力する
//              seriesStr +="{label: '" + counterId + ":" +colNameMap.get(counterId) + "',},\n";
            }
          }
          System.out.println(seriesStr);
        }
		si.getServerConnection().logout();
	}
	
	private static Map getCounterInfoMap(PerformanceManager perfMgr){
		 
	    Map infoMap = new HashMap();
	    //系列情報を取得(取得されるリストには仮想マシンで取得可能なもの意外も含まれます。)
	    pcis =  perfMgr.getPerfCounter();
	    for (PerfCounterInfo pci :pcis ){
	      infoMap.put(pci.getKey(),pci.getGroupInfo().getLabel()+":"+pci.getNameInfo().getLabel());
	    }
	    return infoMap;
	 
	  }
	
	/*
	 * 1 : Usage (cpu) in Percent (rate)
			...
			336 : Queue write latency (disk) in Millisecond (absolute)
			337 : Physical device command latency (disk) in Millisecond (absolute)
			338 : Kernel command latency (disk) in Millisecond (absolute)
	 */
	private static void printInfoMap(PerformanceManager perfMgr){
		
	PerfCounterInfo[] perfCounters = perfMgr.getPerfCounter();
	for (int i = 0; i < perfCounters.length; i++) {
		PerfCounterInfo perfCounterInfo = perfCounters[i];
		String perfCounterString = perfCounterInfo.getNameInfo().getLabel() + " (" + perfCounterInfo.getGroupInfo().getKey() + ") in "
				+ perfCounterInfo.getUnitInfo().getLabel() + " (" + perfCounterInfo.getStatsType().toString() + ")";
			System.out.println(perfCounterInfo.getKey() + " : " + perfCounterString);
	}
	
	}
	private static void printInfoMaps(PerformanceManager pm){
		
		Map<String, PerfCounterInfo> result = new HashMap<String, PerfCounterInfo>();
		PerfCounterInfo[] counters = pm.getPerfCounter();
		if (counters != null)
		{
		for (PerfCounterInfo counter : counters) 
		{
		String key = counter.getGroupInfo().getKey() + "." + counter.getNameInfo().getKey() + "." + counter.getRollupType().toString();
		result.put(key, counter);
		}
		}
	System.out.println();
		
			
		
	}
	
	
}